package com.betterjr.modules.customer.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.modules.account.entity.CustOperatorInfo;
import com.betterjr.modules.account.service.CustOperatorService;
import com.betterjr.modules.customer.dao.CustBaseConfigureMaaper;
import com.betterjr.modules.customer.entity.CustBaseConfigure;

@Service
public class CustBaseConfigureService extends BaseService<CustBaseConfigureMaaper, CustBaseConfigure> {

    @Autowired
    private CustOperatorService operatorService;

    /**
     * 
     * @Title: findOperatorByCustIdentifition 
     * @Description: 通过企业标识和服务类型查询操作员信息 
     * @param anCustIdentifition
     * @param anServicerType
     * @param anUserCode
     * @return 
     * @throws 
     * @author xuyp
     * @date 2018年7月6日 下午2:47:29
     */
    public CustOperatorInfo findOperatorByCustIdentifition(String anCustIdentifition, String anServicerType,
            String anUserCode) {

        CustBaseConfigure configure = queryCustConfiguration(anCustIdentifition, anServicerType, "id desc");

        if (configure != null && configure.getId() != null) {
            List<CustOperatorInfo> operators = operatorService.queryOperatorInfoByCustNo(configure.getCustNo());
            if (!Collections3.isEmpty(operators)) {

                if (StringUtils.isBlank(anUserCode)) return Collections3.getFirst(operators);

                for (CustOperatorInfo custOperatorInfo : operators) {
                    if (custOperatorInfo.getOperCode().equals(anUserCode)) return custOperatorInfo;
                }

            }

        }

        return null;

    }

    @SuppressWarnings("unchecked")
    private CustBaseConfigure queryCustConfiguration(String anCustIdentifition, String anServicerType,
            String anOrderby) {
        if (StringUtils.isNoneBlank(anCustIdentifition) && StringUtils.isNoneBlank(anServicerType)) {

            if (StringUtils.isBlank(anOrderby)) anOrderby = "id desc";

            Map map = QueryTermBuilder.newInstance().put("custIdentifition", anCustIdentifition)
                    .put("servicerType", anServicerType).put("businStatus", "1").build();

            List<CustBaseConfigure> configure = this.selectByProperty(map, anOrderby);

            return Collections3.getFirst(configure);
        }

        return null;
    }

}
